//
//  LXChooseBtnTableViewCell.m
//  ZuLinProject
//
//  Created by bancheng on 2021/12/21.
//  Copyright © 2021 LX_App. All rights reserved.
//

#import "LXCommonLabelsTableViewCell.h"
#import "LXAddLabView.h"

@interface LXCommonLabelsTableViewCell()


@property(nonatomic)NSMutableArray *data;

@property(nonatomic)NSMutableArray *selData;

@property(nonatomic)BOOL isEditBtn;

@end


@implementation LXCommonLabelsTableViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier WithData:(NSMutableArray *)data WithSelData:(NSMutableArray *)selData WithEditIng:(BOOL)isEditBtn {
    
    self = [super initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
    if (self) {
        
        self.backgroundColor = White_Color;
            
        self.data = data;
        
        self.selData = selData;

        self.isEditBtn = isEditBtn;
        
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 300, 50)];
        titleLab.numberOfLines = 2;
        titleLab.font = Fond12;
        titleLab.text = @"常用标签 (最多可选择5个标签)";
        titleLab.textColor = ColorWithAAAAAA;
        [self.contentView addSubview:titleLab];
        [titleLab addAttributes:TextAttrCorlor(ColorWith333333) forText:@"常用标签" size:[UIFont systemFontOfSize:KHeightScale(16)]];
       
        
        UIButton *editBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth - 115, 0, 100, 50)];
        editBtn.titleLabel.font = Fond12;
        [editBtn setTitle:@"编辑" forState:UIControlStateNormal];
        [editBtn setTitle:@"完成" forState:UIControlStateSelected];

        [editBtn setImage:[UIImage imageNamed:@"carDetail_修改信息"] forState:UIControlStateNormal];
        [editBtn setImage:[UIImage imageNamed:@"remarkSave"] forState:UIControlStateSelected];
        [editBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        if (data.count==0&&isEditBtn==NO) {
            editBtn.hidden = YES;
        }
        else {
            editBtn.hidden = NO;
        }
        [editBtn setTitleColor:ColorWith3C6CFC forState:UIControlStateNormal];
        [self.contentView addSubview:editBtn];
        [editBtn addTarget:self action:@selector(clickEditBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        editBtn.selected = isEditBtn;
        
        UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectMake(15, titleLab.Y_height, kScreenWidth-30, 50)];
        [self.contentView addSubview:backgroundView];
        
        CGFloat backgroundView_H = 0;
        
        
        NSMutableArray *ary = [data mutableCopy];
        
        
        if (ary.count < 20 && !isEditBtn) {
            [ary addObject:@{
                @"title":@"+ 添加",
                @"id":@"110"
            }];
        }
        // 间距
        CGFloat margin = 10;
        CGFloat btnW = backgroundView.width / 4 - 8;
        CGFloat btnH = KHeightScale(38);
        
       
        
        
        for (int i = 0; i < ary.count; i++) {
           
            
            NSInteger row = i/4;
            NSInteger col = i%4;
            
            
            CGFloat btnX =  col  * (btnW + margin) ;
            CGFloat btnY =  row * (btnH + margin);
            
            NSDictionary *dic = ary[i];
            NSString *title = dic[@"title"];
            
            
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(btnX, btnY, btnW, btnH)];
            [btn setTitle:title forState:UIControlStateNormal];
            
            // 把数据源id当做tag,以便回调时方便实用
            btn.tag = [dic[@"id"] integerValue];
            [btn setTitleColor:ColorWithAAAAAA forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
            btn.titleLabel.font = Fond14;
            [btn setBackgroundColor:ColorWithF5F5F5];
            btn.layer.cornerRadius = 4;
            btn.layer.masksToBounds = YES;
            [btn addTarget:self action:@selector(clickLabsBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            [backgroundView addSubview:btn];
            
            if ([dic[@"isSel"] boolValue]) {
                btn.selected = YES;
                [btn setBackgroundColor:mainColor];
            
            }
            
            // 绑定参数
            objc_setAssociatedObject(btn, @"selBtn", dic, OBJC_ASSOCIATION_RETAIN_NONATOMIC);

            
            if (!ObjectIsEmpty(self.selData)) {
                
                for (int i = 0; i < self.selData.count; i++) {
                    NSString *tag = self.selData[i];
                    if([tag isEqualToString:btn.titleLabel.text]){
                        UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(btn.X_width - 7, btn.Y - 7, 14, 14)];
                        lab.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.6];
                        [lab addCorner:7];
                        lab.textAlignment = NSTextAlignmentCenter;
                        lab.textColor = UIColor.whiteColor;
                        lab.font = [UIFont systemFontOfSize:8];
                        NSInteger o = i;
                        lab.text = [NSString stringWithFormat:@"%@",@(++o)];
                        [backgroundView addSubview:lab];
                    }
                }
                NSLog(@"");
                
            }
           
           
            
            
            backgroundView_H = btn.Y_height + margin;
            
        }
        backgroundView.height = backgroundView_H;
        
    }
    return self;
}

//MARK: 点击编辑按钮
-(void)clickEditBtnAction:(UIButton *)sender{
    
    sender.selected = !sender.isSelected;
    self.isEditBtn = sender.isSelected;
    if (self.clickBtnBlock) {
        self.clickBtnBlock(self.isEditBtn);
    }
    
}
//MARK: 编辑标签
-(void)editLabsView:(UIButton *)sender{
    LXAddLabView *view = [[NSBundle mainBundle] loadNibNamed:@"LXAddLabView" owner:self options:nil].firstObject;
    view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    view.viewTitleLab.text = @"编辑标签";
    view.textField.text = sender.titleLabel.text;
    [view.cancelBtn setTitle:@"删除" forState:UIControlStateNormal];

    [view setClickConfirmBlock:^(NSString * _Nonnull str) {
        NSMutableDictionary *dic = objc_getAssociatedObject(sender, @"selBtn");
        [dic setValue:str forKey:@"title"];
        
        
        // 得到原始标签的下标
//        NSUInteger idnex = [self.selData indexOfObject:sender.titleLabel.text];
        // 替换修改的文字
        if (!ObjectIsEmpty(self.selData)) {
            [self.selData replaceObjectAtIndex:[self.selData indexOfObject:sender.titleLabel.text] withObject:str];
        }
        
        // 更新标签
        [MSNetworkManager getRevertUrl:POST_UpdateLabTags params:@{@"oldTag":sender.titleLabel.text,@"newTag":str} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:NO];
        
        if (self.clickBtnBlock) {
            self.clickBtnBlock(self.isEditBtn);
        }
        
        
    }];
    [view setClickCancelBlock:^(NSString * _Nonnull str) {
        NSMutableDictionary *dic = objc_getAssociatedObject(sender, @"selBtn");
        [self.data removeObject:dic];
        [self.selData removeObject:str];
        
        
        if (self.clickBtnBlock) {
            self.clickBtnBlock(self.isEditBtn);
        }
        // 删除标签
        [MSNetworkManager getRevertUrl:POST_DelLabTags params:@{@"tag":sender.titleLabel.text} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:NO];
        
        
        
    }];
    [[BaseViewController getCurrentVC].view addSubview:view];
}
// MARK: 添加标签
-(void)addLabsView{
    
   
   
    LXAddLabView *view = [[NSBundle mainBundle] loadNibNamed:@"LXAddLabView" owner:self options:nil].firstObject;
    view.viewTitleLab.text = @"编辑标签";
    [view.cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
    [view setClickConfirmBlock:^(NSString * _Nonnull str) {
        if (ObjectIsEmpty(self.data)) {
            [self.data addObject:@{
                @"title":str,
                @"isSel":@(NO),
                @"id":@"1",
            }.mutableCopy];
        }
        else {
            
            NSArray *titleAry = [self.data valueForKey:@"title"];
            if ([titleAry containsObject:str]) {
                showAlert(@"该标签已存在");
                return;
            }
            
            
            NSDictionary *dic = self.data.lastObject;
            NSInteger Id = [dic[@"id"] integerValue];
            [self.data addObject:@{
                @"title":str,
                @"isSel":@(NO),
                @"id":[NSString stringWithFormat:@"%@",@(++Id)],
            }.mutableCopy];
            
        }
        // 新增标签
        [MSNetworkManager getRevertUrl:POST_SaveLabTags params:@{@"tag":str} success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
            
        } failure:^(NSUInteger code, NSString * _Nonnull message) {
        } withShowHud:NO];
        
        if (self.clickBtnBlock) {
            self.clickBtnBlock(self.isEditBtn);
        }
        
        
        
    }];
    [[BaseViewController getCurrentVC].view addSubview:view];
    return;
}
// MARK: 点击标签
-(void)clickLabsBtnAction:(UIButton *)sender{
    
   
    // 点击添加按钮
    if (sender.tag == 110) {
        [self addLabsView];
        return;
    }
    else if (self.isEditBtn == YES){
        [self editLabsView:sender];
        return;
    }
    
    
    // 如果选中的大于五个
    if(self.selData.count >= 5 && !sender.isSelected){
        showAlert(@"最多可选择五个标签");
        return;
    }
    
    
    sender.selected = !sender.isSelected;

    NSMutableDictionary *dic = objc_getAssociatedObject(sender, @"selBtn");
    [dic setValue:@(sender.isSelected) forKey:@"isSel"];
    
    if (sender.isSelected) {
        [self.selData addObject:sender.titleLabel.text];
    }
    else {
        [self.selData removeObject:[NSString stringWithFormat:@"%@",sender.titleLabel.text]];
    }
    
    
    // 查找数组中包含某个key的字典
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"id MATCHES[cd] %@", [NSString stringWithFormat:@"%@",@(sender.tag)]];
//    NSMutableDictionary *result = [[self.data filteredArrayUsingPredicate:predicate] firstObject];
//    if (!ObjectIsEmpty(result)) {
//        [result setValue:@(sender.isSelected) forKey:@"isSel"];
//    }
    
    if(sender.isSelected){
        [sender setBackgroundColor:mainColor];
    }
    else {
        [sender setBackgroundColor:ColorWithF5F5F5];
    }

    if (self.clickBtnBlock) {
        self.clickBtnBlock(self.isEditBtn);
    }
 
}

+(CGFloat)height:(NSArray *)data WithIsEdit:(BOOL)isEdit{
    
    
    NSInteger dataCount = data.count;

    if (dataCount < 20 && !isEdit) {
        dataCount++;
    }
    
    CGFloat height = dataCount/4 * kComHeight;
    if (dataCount % 4!=0) {
        height = (dataCount/4 + 1) * kComHeight;
    }
//    CGFloat count = dataCount/4.0;
//    if (count > 1) {
//        return height - (5 * ceil(count));
//    }
    return height + 50;
}


@end
